package com.wk.code.wkserver.config;

import com.wk.code.wkserver.constant.Constant;
import com.wk.code.wkserver.interceptor.AuthenticationInterceptor;
import com.wk.code.wkserver.service.ISysIgnorePathService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.BoundListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;

/**
 * @author wq
 * @version 1.0
 * @date 2020/12/29 11:03
 */
@Configuration
@Slf4j
@SuppressWarnings("all")
public class WebConfig implements WebMvcConfigurer {

    @Resource
    private AuthenticationInterceptor tokenInterceptor;

    @Resource
    private ISysIgnorePathService sysIgnorePathService;

    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        //注册自定义拦截器，添加拦截路径和排除拦截路径
        registry.addInterceptor(tokenInterceptor).
                addPathPatterns("/**").
                excludePathPatterns("/doc.html").
                excludePathPatterns("/swagger-resources/**").
                excludePathPatterns("/favicon.ico").
                excludePathPatterns("/webjars/**");
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //配置拦截器访问静态资源
        registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/favicon.ico").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

    @PostConstruct
    public void cachePaths() {
        redisTemplate.delete(Constant.IGNORE_CACHE_PATH);
        BoundListOperations listOps = redisTemplate.boundListOps(Constant.IGNORE_CACHE_PATH);
        if (!redisTemplate.hasKey(Constant.IGNORE_CACHE_PATH)) {
            List<String> paths = sysIgnorePathService.acquirePaths();
            // 将整个列表存入redis中
            listOps.leftPushAll(paths);
        }
    }


}
